<template>
  <div style="padding-top: 10px;background-color: #ffffff">
    <!-- 表单 -->
    <el-form :inline="true" :model="page" class="demo-form-inline" style="padding-left: 150px;white-space: nowrap">
      <el-form-item label="">
        <el-input v-model="page.queryString" placeholder="姓名 / 账号 / 电话号码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" icon="el-icon-circle-plus-outline" @click="addUserInfo">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" icon="el-icon-refresh" @click="replaseMent">重置</el-button>
      </el-form-item>
    </el-form>
      <el-table :data="tableData" :pagination="false" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="50%" align="center" />
        <el-table-column prop="id" label="编号" width="50" align="center">
          <template v-slot="scope">
            <el-tag>
              {{scope.row.id}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180" align="center"></el-table-column>
        <el-table-column prop="username" label="账号" width="180" align="center"></el-table-column>
        <el-table-column prop="sex" label="性别" width="140" align="center">
          <template v-slot="scope">
            <el-tag type="danger">
              <span>{{ scope.row.sex === 1 ? '男' : '女' }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roleId" label="类型" width="198" align="center">
          <template v-slot="scope">
<!--            <span>{{ scope.row.roleId === 2 ? '管理员' : '内部用户' }}</span>-->
            <el-switch
              style="display: block"
              v-model="switchValue[scope.$index]"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="2"
              inactive-value="3"
              active-text="管理员"
              inactive-text="普通用户"
              @change="handleChangeType(scope.row.roleId, scope.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <!--<el-table-column prop="image" label="图像" width="180"></el-table-column>-->
        <el-table-column prop="image" label="图像" width="180" align="center">
          <template v-slot="{ row }">
            <img :src="row.imageUrl" width="100px" height="70px">
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮件" width="200" align="center"></el-table-column>
        <el-table-column prop="phone" label="电话号码" width="140" align="center"></el-table-column>
        <el-table-column prop="license" label="许可证或执照号码" width="200" align="center"></el-table-column>
<!--        <el-table-column prop="password" label="密码" width="200" align="center"></el-table-column>-->
        <el-table-column prop="prescriptionRecords" label="处方记录" width="250" align="center"></el-table-column>
        <el-table-column prop="medicalHistory" label="医疗历史" width="250" align="center"></el-table-column>
        <el-table-column el-table-column fixed="right" label="操作" width="270" align="center">
          <template v-slot="scope">
            <el-button type="primary" size="mini" icon="el-icon-paperclip" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              icon="el-icon-info"
              icon-color="red"
              @confirm="deleteItem(scope.row)"
              style="margin-left: 5px;white-space: nowrap"
            >
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
<!--   添加 -->
    <div style="white-space: nowrap;vertical-align: middle">
      <el-dialog :visible.sync="addDialogFormVisible" title="新增弹框" :modal="false" :width="'50%'">
        <el-row :gutter="15">
          <el-form ref="elForm" :model="dataList" :rules="rules" status-icon size="medium" label-width="100px">
            <el-col :span="11">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="dataList.name" placeholder="姓名" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="账号" prop="username">
                <el-input v-model="dataList.username" placeholder="账号" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="下拉选择" prop="sex">
                <el-select v-model="dataList.sex" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                  <!-- 注意：el-option 设置了 value 属性 -->
                  <el-option v-for="(item, index) in sex" :key="index" :label="getLabel(item)" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="密码" prop="password">
                <el-input v-model="dataList.password" placeholder="密码" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="dataList.email" placeholder="邮箱" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="电话号码" prop="phone">
                <el-input v-model="dataList.phone" placeholder="电话号码" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="单行文本" prop="license">
                <el-input v-model="dataList.license" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
<!--            <el-col :span="10">-->
<!--              <div class="custom-upload-container">-->
<!--                <div class="upload-title">头像上传</div>-->
<!--                <el-upload-->
<!--                  class="avatar-uploader"-->
<!--                  :action="insertBaseURL + '/userImage'"-->
<!--                  :show-file-list="false"-->
<!--                  :on-success="handleAvatarSuccess"-->
<!--                  :before-upload="beforeAvatarUpload">-->
<!--                  <img v-if="imageUrl" :src="imageUrl" class="avatar">-->
<!--                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--                </el-upload>-->
<!--              </div>-->
<!--            </el-col>-->
            <el-col :span="22">
              <el-form-item label="多行文本" prop="prescriptionRecords">
                <el-input v-model="dataList.prescriptionRecords" type="textarea" placeholder="请输入多行文本"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="多行文本" prop="medicalHistory">
                <el-input v-model="dataList.medicalHistory" type="textarea" placeholder="请输入多行文本"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
        <div slot="footer">
          <el-button @click="addDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addDialogUser">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--分页-->
    <div style="text-align: right;padding: 10px 20px;" >
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="page.page"
        :page-sizes="[5, 10, 15, 25, 30]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total" />
    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="编辑弹框" :modal="false" :width="'40%'">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules"  status-icon size="medium" label-width="100px">
          <el-col :span="11">
            <el-form-item label="编号" prop="id">
              <el-input v-model="formData.id" placeholder="请输入姓名" disabled="disable" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入姓名" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="账号" prop="username">
              <el-input v-model="formData.username" placeholder="请输入单行文本" disabled="disabled" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                <!-- 注意：el-option 设置了 value 属性 -->
                <el-option v-for="(item, index) in sex" :key="index" :label="getLabel(item)" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="单行文本" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="单行文本" prop="license">
              <el-input v-model="formData.license" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <div class="custom-upload-container">
              <div class="upload-title">头像上传</div>
              <el-upload
                class="avatar-uploader"
                :action="insertBaseURL+'/image/userImage'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="22">
            <el-form-item label="多行文本" prop="prescriptionRecords">
              <el-input v-model="formData.prescriptionRecords" type="textarea" placeholder="请输入多行文本"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="多行文本" prop="medicalHistory">
              <el-input v-model="formData.medicalHistory" type="textarea" placeholder="请输入多行文本"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import zhCn from 'element-ui/lib/locale/lang/zh-CN'
import request from '../../api/request'
import { userInfo } from '@/api/user'
import { getToken } from '@/api/gettoken'

export default {
  data () {
    return {
      switchValue: [],
      locale: zhCn,
      sexModel: '',
      dataList: {
        sex: '',
        imageUrl: ''
      }, // 新增
      insertBaseURL: '',
      dialogFormVisible: false,
      addDialogFormVisible: false,
      visible: false,
      formLabelWidth: '120px',
      tableData: [],
      form: [],
      imageUrl: '',
      page: {
        total: 10,
        currentPage: 1,
        pageSize: 5,
        queryString: ''
      },
      formData: {
        sex: '',
        imageUrl: ''
      },
      sex: [
        { value: 1, label: '男' },
        { value: 0, label: '女' }
      ],
      rules: {
        id: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
  },
  props: [],
  created () {
    this.insertBaseURL = this.$requestcode.defaults.baseURL
    this.getData()
    // this.getToken()
  },
  computed: {
  },
  methods: {
    getLabel (item) {
      // 这个函数应该根据数据库的值返回对应的标签，例如 "男" 或 "女"
      if (item.value === 1) {
        return '男'
      } else {
        return '女'
      }
    },
    getToken () {
      getToken().then(resp => {
        if (resp.data.flag === true) {
          this.$message.error(resp.data.message)
        } else {
          this.$message.error(resp.data.message)
        }
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    handleUpdate (row) {
      this.dialogFormVisible = true
      const token = localStorage.getItem('token')
      const _this = this
      request.get('/user/' + row.id, { headers: { Authorization: 'Bearer ' + token } }).then((resp) => {
        _this.formData = resp.data.data // Assuming the response contains user data
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    handleEdit () {
      // const data = this.$cookies.get('rememberMe')
      const token = localStorage.getItem('token')
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          request.put('/user/infos', this.formData, { headers: { Authorization: 'Bearer ' + token } }).then((resp) => {
            this.dialogFormVisible = false
            if (resp.data.flag === true) {
              this.$message.success(resp.data.message)
              // this.setRememberMeCookie(resp.data.data)
              this.getData()
            } else {
              this.$message.error(resp.data.message)
            }
          })
            .catch(error => {
              console.error('Error:', error)
            })
        }
      })
    },
    addUserInfo () {
      this.addDialogFormVisible = true
      this.dataList = {}
    },
    // 添加
    addDialogUser () {
      const token = localStorage.getItem('token')
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          request.post('/user/addUser', this.dataList,
            {
              headers: {
                accept: 'application/json',
                Authorization: 'Bearer ' + token
              }
            }).then((resp) => {
            if (resp.data.flag === true) {
              this.$message.success(resp.data.message)
              this.addDialogFormVisible = false
              this.getData()
            } else {
              this.$message.error(resp.data.message)
            }
          }).catch(error => {
            this.handleAxiosError(error)
          })
        }
      })
    },
    onSubmit () {
      this.page.currentPage = 1
      this.getData()
    },
    replaseMent () {
      this.page.queryString = ''
      this.getData()
    },
    async getData () {
      const infoData = {
        currentPage: this.page.currentPage,
        pageSize: this.page.pageSize,
        paramsString: this.page.queryString
      }
      try {
        await userInfo(infoData).then(resp => {
          const data = resp.data
          this.page.total = data.total
          this.tableData = data.rows
          this.switchValue = data.rows.map(item => String(item.roleId))
          // alert(this.switchValue)
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    deleteItem (row) {
      // const data = this.$cookies.get('rememberMe')
      const token = localStorage.getItem('token')
      request.delete('/user/' + row.id, { headers: { Authorization: 'Bearer ' + token } }).then(resp => {
        if (resp.data.flag === true) {
          this.visible = false
          this.$message({
            type: 'success',
            message: resp.data.message
          })
        }
        this.getData()
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    handleChangeType (vale, id) {
      this.$confirm('此操作将修改该用户的角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          roleId: (vale === 2) ? '3' : '2',
          id: id
        }
        // alert(JSON.stringify(data))
        const token = localStorage.getItem('token')
        request.post('/user/updateUserType', data, { headers: { Authorization: 'Bearer ' + token } }).then(res => {
          if (res.data.flag === true) {
            this.$message({
              type: 'success',
              message: res.data.message,
              center: true,
              offset: 85
            })
            this.getData()
            return
          }
          this.$message({
            type: 'danger',
            message: res.data.message,
            center: true,
            offset: 85
          })
          this.getData()
        }).catch(error => {
          this.handleAxiosError(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
        this.getData()
      })
      // const roleId = (vale === 2) ? '3' : '2'
      // alert(JSON.stringify(data))
    },
    handlePageSizeChange (pageSize) {
      this.page.pageSize = pageSize
      this.page.currentPage = 1 // 重置为第一页
      this.getData()
    },
    handleCurrentPageChange (currentPage) {
      this.page.currentPage = currentPage
      this.getData()
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      this.formData.imageUrl = res.data
    },
    beforeAvatarUpload (file) {
      const allowedFormats = ['image/jpeg', 'image/png', 'image/gif'] // 允许的文件格式

      const isAllowedFormat = allowedFormats.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isAllowedFormat) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isAllowedFormat && isLt2M
    },
    handleSelectionChange () {},
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message({
          type: 'error',
          message: '网络请求失败，请稍后重试',
          center: true,
          offset: 50
        })
      } else {
        // 处理其他类型的错误
        this.$message({
          type: 'error',
          message: '网络请求失败，发生错误，请稍后重试',
          center: true,
          offset: 50
        })
      }
    }
  }
}
</script>

<style scoped>
/*@import "../../assets/css/style.css";*/
.avatar-uploader .el-upload {
  border: 1px dashed #d97979;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border: 1px dashed #409EFF; /* 修改为:hover时的边框颜色 */
}

.avatar-uploader-icon {
  font-size: 25px;
  color: #2667c4;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #bcbebf;
  margin: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.custom-upload-container {
  display: flex;
  align-items: center;
  margin-left: 25px;
}

.upload-title {
  margin-left: 10px;
  white-space: nowrap;
}
</style>
